//
//  OAuthModel.swift
//  swift-微博
//
//  Created by chenrin on 2016/12/19.
//  Copyright © 2016年 zhuoheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthModel: NSObject,NSCoding{
    //用户授权的唯一票据，用于调用微博的开放接口
    var access_token = ""
    //access_token的生命周期，单位是秒数。
    var expires_in : NSNumber?{
        didSet{
            expiresData = Date(timeIntervalSinceNow: expires_in!.doubleValue)
        }
    }
    //授权用户的UID
    var uid = ""
    
    //保存用户过期时间
    var expiresData : Date?
    
    //用户的头像
    var avatar_large : String?
    //用户昵称
    var screen_name : String?
    
    
    
    override init(){
        
    }
    //自定义构造方法
    init(dict:[String:Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    //model 中不存在dict中的值，必须调用此方法，不然会崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    ///返回用户是否登录
   class func userLogin() -> Bool {
        return OAuthModel.getAccount() != nil
    }
   
    // MARK:- 请求用户数据
    func loadUserInfo() {
        assert(access_token != "", "没有授权")
        let param = ["access_token":access_token,"uid":uid]
        NetworkTools.requestData(methodType: .GET, urlString: "https://api.weibo.com/2/users/show.json", parameters: param, finishedCallback: {(result) in
            print(result)
            guard let resultDict = result as? [String:Any] else{
                SVProgressHUD.showInfo(withStatus: "网络不给力...")
                return
            }
            self.screen_name = resultDict["screen_name"] as? String
            self.avatar_large = resultDict["avatar_large"] as? String
            self.saveAccount()
            
            
        })
    }
    
    // MARK:- 保存和读取数据
    //保存
    
    func saveAccount() {
        let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
        let filePath = path + "/account.plist"
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    //读取
    static var account:OAuthModel?
   class func getAccount()->OAuthModel? {
    //1.判断是否已经加载过
    if account != nil {
        return account
    }
    //2.解归档
        let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
        let filePath = path + "/account.plist"
         account = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? OAuthModel
    //判断授权信息是否过期
    
    if account?.expiresData?.compare(Date()) == ComparisonResult.orderedAscending {
        //已经过期
        return nil
    }
    
        return account
    }
    
    // MARK:- NSCoding
    //将对象写入文件中
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expiresData, forKey: "expiresData")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    //将对象从文件中读取
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as! String
        expires_in = aDecoder.decodeObject(forKey: "expires_in") as? NSNumber
        uid = aDecoder.decodeObject(forKey: "uid") as! String
        expiresData = aDecoder.decodeObject(forKey: "expiresData") as? Date
        avatar_large = (aDecoder.decodeObject(forKey: "avatar_large") as? String)
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
    }
    
}
